package javamobile.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybeans.dao.DAOException;

import javamobile.model.*;
import javamobile.util.Utilities;

public class CreateBillAction extends Action{

	private DAOFactory factory;
	
	public CreateBillAction(Model model) {
		factory = model.getDAOFactory();
	}
	
	@Override
	public String getName() {return "create.do";}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> perform(Map<String, Object> input) {
		System.out.println("Performing create action!");
		Map<String, Object> output = new HashMap<String, Object>();
		List<String> errors = new ArrayList<String>();
		output.put("errors", errors);
		
		String username = (String) input.get("username");
		String payer_str = (String) input.get("payer");
		double amount = (double) input.get("amount");
		String date = (String) input.get("date"); // Check date format at front end!
		String description = (String) input.get("description");
		List<String> emails = (List<String>) input.get("emails");
		List<Double> amounts = (List<Double>) input.get("amounts");
		String location = (String) input.get("location");
		
		int ways = (int) input.get("ways");
		
		try {
			User user = factory.lookupUser(username);
			if (user == null) {
				errors.add("User "+username+" not found");
				return output;
			}
			
			User payer = factory.lookupUser(payer_str);
			if (payer == null) {
				errors.add("User "+payer_str+" not found");
				return output;
			}
			
			Bill bill = new Bill(user.getUserID(), payer.getUserID(), amount, date, description, BillState.SAVED, date, location);
			BillSplit[] bs = new BillSplit[ways];
			for (int i = 0; i < ways; i++) {
				User oneSpliter = factory.lookupUser(emails.get(i));
				if (oneSpliter == null) {
					errors.add("User "+emails.get(i)+" not found");
					return output;
				}
				if (oneSpliter.getUserID() == payer.getUserID()) {
					errors.add("You don't need to add the payer. The rest of the bill is the payer's.");
					return output;
				}
				bs[i] = new BillSplit(-1, payer.getUserID(), oneSpliter.getUserID(), amounts.get(i), BillState.SAVED);
			}
    		if (!Utilities.checkDuplicate(emails.toArray())) {
    			errors.add("Duplicate person to split with.");
    			return output;
    		}
            int billID = factory.saveBill(bill, bs);
            factory.sendBill(billID);
        }
		catch (DAOException e) {
        	errors.add(e.getMessage());
        	return output;
	    }

		return output;
	}

}